package indi.storyoftime.rasite.controller;


import indi.storyoftime.rasite.controller.support.ImageException;
import indi.storyoftime.rasite.entity.Image;
import indi.storyoftime.rasite.service.impl.AlbumService;
import indi.storyoftime.rasite.service.impl.ImageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@CrossOrigin
@RestController
@RequestMapping("/images")
public class ImageController {

    @Value("${host.story-image-host}")
    private String IMAGE_HOST;
    private static final RestTemplate template = new RestTemplate();

    @Autowired
    private ImageService imageService;
    @Autowired
    private AlbumService albumService;

    /**
     * 根据id获取image。
     */
    @GetMapping(value = "/{id}", produces = "application/json;charset=UTF-8")
    public Image getImageById(@PathVariable Integer id) {
        Image image = imageService.getImageById(id);
        if (!Objects.nonNull(image)) {
            throw new ImageException("未找到image: " + id);
        }
        return image;
    }

    /**
     * 分页获取image。
     */
    @GetMapping(value = "", produces = "application/json;charset=UTF-8")
    public List<Image> getImages(
            @RequestParam(value = "pageNo", required = false) Integer pageNo,
            @RequestParam(value = "pageSize", required = false) Integer pageSize,
            @RequestParam(value = "limit", required = false) Integer limit,
            @RequestParam(value = "offset", required = false) Integer offset,
            @RequestParam(value = "orderBy", required = false) String orderBy,
            @RequestParam(value = "desc", required = false, defaultValue = "true") Boolean desc) {
        List<Image> images;
        if (pageNo != null && pageSize != null) {
            // 分页查询
            images = imageService.getImagesByPage(pageNo, pageSize);
        } else if (limit != null) {
            // 使用limit查询
            if (offset == null) {
                offset = 0;
            }
            images = imageService.getImagesByLimit(offset, limit);
        } else {
            images = imageService.getImages();
        }

        // TODO:拼装排序规则
        if(Objects.nonNull(orderBy)) {
            // TODO
        }

        return images;
    }

    /**
     * 创建image。 TODO: 添加可选参数，带入图片album_id，并且更新album封面。
     */
    @PostMapping(value = "", produces = "application/json;charset=UTF-8")
    public List<Image> postImage(
            @RequestParam("file") MultipartFile[] files,
            @RequestParam(value = "albumId", required = false) Integer albumId) {
        List<Image> imageList = new ArrayList<>();
        String url = IMAGE_HOST + "image";

        if (files.length > 0) {
            for (MultipartFile file : files) {

                // 上传图片到image-host
                HttpHeaders uploadHeaders = new HttpHeaders();
                uploadHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
                MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
                map.add("file", file.getResource());
                HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(map, uploadHeaders);
                ResponseEntity<ImageDTO> response = template.postForEntity(url, entity, ImageDTO.class);
                ImageDTO imageDTO = response.getBody();

                Image image = imageService.parseImage(file);

                if (image != null && imageDTO != null) {
                    String imageId = imageDTO.getImageId();
                    image.setUrl(IMAGE_HOST + "image/raw/" + imageId);
                    image.setThumbnailUrl(IMAGE_HOST + "image/thumb/" + imageId);

                    // 设置所属相册
                    if (albumService.isAlbumAvailable(albumId)) {
                        image.setAlbumId(albumId);
                    }

                    if (imageService.createImage(image) != 0) {
                        imageList.add(image);
                    }
                }
            }
        }

        return imageList;
    }

    /**
     * 根据id更新image。
     */
    @PutMapping(value = "/{id}", produces = "application/json;charset=UTF-8")
    public Image updateImageById(@PathVariable Integer id, @RequestBody Image image) {
        if (imageService.updateImageById(id, image) == 1) {
            return imageService.getImageById(id);
        } else {
            throw new ImageException("未找到image: " + id);
        }

    }

    /**
     * 根据id删除image。
     * TODO: 确定是否需要触发图床的删除
     */
    @DeleteMapping(value = "/{id}", produces = "application/json;charset=UTF-8")
    public void deleteImageById(@PathVariable Integer id) {
        imageService.deleteImageById(id);
    }

    // TODO: 调试用
    @GetMapping("/upload")
    @ResponseBody
    public String getUpload() {
        return "<html><form method=post enctype=multipart/form-data action=\"/images\">"
                + "<input type=file name=file multiple>"
                + "<input type=submit value=UpUp>"
                + "</form></html>";
    }

    // TODO: 转成引入image-host的依赖
    static class ImageDTO {
        private String imageId;

        public String getImageId() {
            return imageId;
        }

        public void setImageId(String imageId) {
            this.imageId = imageId;
        }
    }
}
